/*
 * Powered By cuichen
 * Since 2014 - 2018
 */
package com.seeyoui.kensite.bussiness.orderlang.outbound.controller;

import java.sql.*;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.seeyoui.kensite.common.util.DateUtils;
import com.seeyoui.kensite.common.util.StringUtils;
import com.seeyoui.kensite.common.constants.StringConstant;
import com.seeyoui.kensite.common.base.domain.EasyUIDataGrid;
import com.seeyoui.kensite.common.base.controller.BaseController;
import com.seeyoui.kensite.common.util.RequestResponseUtil;
import com.seeyoui.kensite.common.util.excel.ExportExcel;

import org.apache.lucene.index.Term;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import com.seeyoui.kensite.common.base.domain.Page;
import com.seeyoui.kensite.framework.luence.domain.LuceneDocument;
import com.seeyoui.kensite.framework.luence.util.LuceneUtils;
import com.seeyoui.kensite.bussiness.orderlang.delivery.domain.DeliveryExamineProductVO;
import com.seeyoui.kensite.bussiness.orderlang.order.domain.Order;
import com.seeyoui.kensite.bussiness.orderlang.outbound.domain.Outbound;
import com.seeyoui.kensite.bussiness.orderlang.outbound.domain.OutboundProductVO;
import com.seeyoui.kensite.bussiness.orderlang.outbound.domain.OutboundVO;
import com.seeyoui.kensite.bussiness.orderlang.outbound.service.OutboundService;
import com.seeyoui.kensite.bussiness.orderlang.productAttachment.domain.ProductAttachment;
import com.seeyoui.kensite.bussiness.orderlang.productAttachment.service.ProductAttachmentService;
import com.seeyoui.kensite.bussiness.orderlang.productSpec.domain.ProductSpec;
import com.seeyoui.kensite.bussiness.orderlang.productSpec.service.ProductSpecService;
import com.seeyoui.kensite.bussiness.orderlang.productUnit.domain.ProductUnit;
import com.seeyoui.kensite.bussiness.orderlang.productUnit.service.ProductUnitService;
/**
 * Outbound
 * @author cuichen
 * @version 2.0
 * @since 1.0
 * @date 2018-03-01
 */

@Controller
@RequestMapping(value = "outbound")
public class OutboundController extends BaseController {
	
	@Autowired
	private OutboundService outboundService;
	@Autowired
	private ProductAttachmentService productAttachmentService;
	@Autowired
    private ProductSpecService productSpecService;
	@Autowired
    private ProductUnitService productUnitService;
	/**
	 * 展示列表页面
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("outbound:view")
	@RequestMapping(value = "/{page}")
	public ModelAndView view(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String page) throws Exception {
		return new ModelAndView("bussiness/orderlang/outbound/"+page, modelMap);
	}
	
	/**
	 * 根据ID查询单条数据
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("outbound:select")
	@RequestMapping(value = "/data/{id}")
	@ResponseBody
	public Object data(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String id) throws Exception {
		Outbound outbound = outboundService.findOne(id);
		return outbound;
	}
	
	/**
	 * 根据ID查询单条数据并返回相应表单
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("outbound:view")
	@RequestMapping(value = "/form/{page}/{id}")
	public ModelAndView form(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String page, @PathVariable String id) throws Exception {
		Outbound outbound = outboundService.findOne(id);
		modelMap.put("outbound", outbound);
		return new ModelAndView("bussiness/orderlang/outbound/"+page, modelMap);
	}
	
	/**
     * 出库界面加载商品列表
     * @param modelMap
     * @param module
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/outboundProduct", method=RequestMethod.POST)
    @ResponseBody
    public Object outboundProduct(HttpSession session,
            HttpServletResponse response, HttpServletRequest request,
            ModelMap modelMap, String deliveryId) throws Exception {
        List<OutboundProductVO> outboundProductVOList = outboundService.findOutboundProduct(deliveryId);
        for (OutboundProductVO outboundProductVO : outboundProductVOList) {
            ProductSpec productSpec = new ProductSpec();
            productSpec.setProductPriceId(outboundProductVO.getProductPriceId());
            List productSpecList = productSpecService.findList(productSpec);
            outboundProductVO.setProductSpecList(productSpecList);
        }
        return outboundProductVOList;
    }
	
	/**
	 * 获取列表展示数据
	 * @param modelMap
	 * @param outbound
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("outbound:select")
	@RequestMapping(value = "/list/data", method=RequestMethod.POST)
	@ResponseBody
	public Object listData(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Outbound outbound) throws Exception {
		List<Outbound> outboundList = outboundService.findList(outbound);
		int total = outboundService.findTotal(outbound);
		EasyUIDataGrid eudg = new EasyUIDataGrid();
		eudg.setTotal(String.valueOf(total));
		eudg.setRows(outboundList);
		return eudg;
	}
	
	/**
     * 获取列表展示数据带分页器用于jsp自己做分页
     * 
     * @param modelMap
     * @param outbound
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("warehouse:outbound:view")
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/list/page", method = RequestMethod.POST)
    @ResponseBody
    public Object listPage(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, Outbound outbound,
            String orderCode, String warehouseId, String beginTime, String endTime) throws Exception {
        Map map = new HashMap();
        map.put("orderCode", orderCode);
        map.put("warehouseId", warehouseId);
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("row", outbound.getRow());
        map.put("rows", outbound.getRows());
        List<Order> outboundAsOrderList = outboundService.findListRelationOrder(map);
        int total = outboundService.findTotalRelationOrder(map);
        Page<Outbound> page = new Page<Outbound>(outbound.getPage(), outbound.getRows(), total);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("rows", outboundAsOrderList);
        dataMap.put("page", page);
        return dataMap;
    }
    
    /**
     * 获取列表展示数据带分页器用于jsp自己做分页
     * 
     * @param modelMap
     * @param outbound
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("warehouse:outbound:view")
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/findInboundOrOutboundList", method = RequestMethod.POST)
    @ResponseBody
    public Object findInboundOrOutboundList(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, Outbound outbound,
            String orderCode, String warehouseId, String beginTime, String endTime, String type) throws Exception {
        Map map = new HashMap();
        map.put("orderCode", orderCode);
        map.put("warehouseId", warehouseId);
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("row", outbound.getRow());
        map.put("rows", outbound.getRows());
        List<OutboundVO> outboundAsOrderList = outboundService.findInboundOrOutboundList(map,type);
        for (OutboundVO outboundVO : outboundAsOrderList) {
            String imgId = outboundVO.getProductImgUrl();
            // 查询图片地址
            ProductAttachment productAttachment = new ProductAttachment();
            productAttachment.setProductId(imgId);
            productAttachment.setType("0");
            productAttachment.setSeq("0");
            List<ProductAttachment> productAttachmentList = productAttachmentService.findList(productAttachment);
            if (null != productAttachmentList && productAttachmentList.size()>=0) {
                outboundVO.setProductImgUrl(productAttachmentList.get(0).getUrl());
            }
            // 查询规格
            String productPriceId = outboundVO.getProductPriceId();
            if(!StringUtils.isEmpty(productPriceId)){
                ProductSpec queryProductSpec = new ProductSpec();
                queryProductSpec.setProductPriceId(productPriceId);
                List<ProductSpec> productSpecList = productSpecService.findList(queryProductSpec);
                String specValue = "";
                for (ProductSpec productSpec : productSpecList) {
                    specValue += "," + productSpec.getSpecName()+ " : " +productSpec.getSpecValue();
                }
                if (!StringUtils.isEmpty(specValue)) {
                    outboundVO.setProductPriceId(specValue.substring(1));
                }else{
                    outboundVO.setProductPriceId("");
                }
            }
            // 查询单位
            String bigUnitId = outboundVO.getBigUnitName();
            String littleUnitId = outboundVO.getLittleUnitName();
            if(!StringUtils.isEmpty(bigUnitId)){
                ProductUnit productUnit = productUnitService.findOne(bigUnitId);
                if(null != productUnit && !"".equals(productUnit.getUnitName())){
                    outboundVO.setBigUnitName(productUnit.getUnitName());
                }else{
                    outboundVO.setBigUnitName("");
                }
            }
            if(!StringUtils.isEmpty(littleUnitId)){
                ProductUnit productUnit = productUnitService.findOne(littleUnitId);
                if(null != productUnit){
                    outboundVO.setLittleUnitName(productUnit.getUnitName());
                }else{
                    outboundVO.setLittleUnitName("");
                }
            }
            if(!StringUtils.isEmpty(outboundVO.getBigUnitName()) && !StringUtils.isEmpty(outboundVO.getLittleUnitName())){
                outboundVO.setBigUnitName(outboundVO.getBigUnitName()+"/");
            }
        }
        int total = outboundService.findTotalInboundOrOutboundList(map,type);
        Page<Outbound> page = new Page<Outbound>(outbound.getPage(), outbound.getRows(), total);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("rows", outboundAsOrderList);
        dataMap.put("page", page);
        return dataMap;
    }
	
	/**
	 * 获取所有数据
	 * @param modelMap
	 * @param outbound
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("outbound:select")
	@RequestMapping(value = "/list/all", method=RequestMethod.POST)
	@ResponseBody
	public Object listAll(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Outbound outbound) throws Exception {
		List<Outbound> outboundList = outboundService.findAll(outbound);
		return outboundList;
	}
	
	/**
     * 订单详情界面加载出库单信息
     * @param modelMap
     * @param outbound
     * @return
     * @throws Exception
     */
    //@RequiresPermissions("outbound:select")
    @RequestMapping(value = "/orderDetailForOutbound", method=RequestMethod.POST)
    @ResponseBody
    public Object orderDetailForOutbound(HttpSession session,
            HttpServletResponse response, HttpServletRequest request,
            ModelMap modelMap, Outbound outbound) throws Exception {
        List<Outbound> outboundList = outboundService.findAll(outbound);
        return outboundList;
    }
	
	/**
	 * 保存新增的数据
	 * @param modelMap
	 * @param outbound
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("outbound:insert")
	@RequestMapping(value = "/save", method=RequestMethod.POST)
	@ResponseBody
	public String save(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Outbound outbound) throws Exception {
		if (!beanValidator(modelMap, outbound)){
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		outboundService.save(outbound);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}
	
	/**
	 * 保存修改的数据
	 * @param modelMap
	 * @param outbound
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("outbound:update")
	@RequestMapping(value = "/update", method=RequestMethod.POST)
	@ResponseBody
	public String update(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Outbound outbound) throws Exception {
		if (!beanValidator(modelMap, outbound)){
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		outboundService.update(outbound);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}
	
	/**
	 * 删除数据库
	 * @param modelMap
	 * @param outboundId
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("outbound:delete")
	@RequestMapping(value = "/delete", method=RequestMethod.POST)
	@ResponseBody
	public String delete(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, String id) throws Exception {
		List<String> listId = Arrays.asList(id.split(","));
		outboundService.delete(listId);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}
	
	/**
	 * 假删除
	 * @param modelMap
	 * @param outbound
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("outbound:delete")
	@RequestMapping(value = "/remove", method=RequestMethod.POST)
	@ResponseBody
	public String remove(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Outbound outbound) throws Exception {
		outboundService.remove(outbound);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}

	/**
	 * 导出Excel数据
	 * @param modelMap
	 * @param outbound
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("outbound:export")
	@RequestMapping(value = "/export")
	public String export(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Outbound outbound) throws Exception {
		String fileName = DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
		List<Outbound> outboundList = outboundService.findAll(outbound);
		new ExportExcel(null, Outbound.class).setDataList(outboundList).write(response, fileName).dispose();
		return null;
	}
}